import * as echarts from '../../../components/ec-canvas/echarts';
import { 
  getSBPWeek, 
  getDBPWeek,
  getGapWeek,
  getRecordWeek,
  Heartgrading
} from '../../../utils/api/BPLControl';
import userBaseInfoState from '../../../stores/userBaseInfo';

Page({
  data: {
    statusBarHeight: 44,
    timeType: 'week',
    dateRange: '',
    currentDate: new Date(),
    
    // 时间偏移量：0表示当前，1表示上一个周期
    daysAgo: 0,
    weeksAgo: 0,
    monthsAgo: 0,
    
    ec: {
      lazyLoad: true
    },
    
    // 平均值数据
    avgSystolic: 0,
    avgDiastolic: 0,
    
    // 表格数据
    tableData: {
      systolic: {
        max: { displayValue: '--', tag: '无', tagClass: '' },
        min: { displayValue: '--', tag: '无', tagClass: '' },
        highest: { displayValue: '--', tag: '无', tagClass: '' }
      },
      diastolic: {
        max: { displayValue: '--', tag: '无', tagClass: '' },
        min: { displayValue: '--', tag: '无', tagClass: '' },
        highest: { displayValue: '--', tag: '无', tagClass: '' }
      },
      pulse: {
        max: { displayValue: '--', tag: '无', tagClass: '' },
        min: { displayValue: '--', tag: '无', tagClass: '' },
        highest: { displayValue: '--', tag: '无', tagClass: '' }
      },
      pulsePressure: {
        max: { displayValue: '--', tag: '无', tagClass: '' },
        min: { displayValue: '--', tag: '无', tagClass: '' },
        highest: { displayValue: '--', tag: '无', tagClass: '' }
      }
    },
    
    // 饼图数据
    pieData: {
      mild: { count: 0, percent: 0 },
      highNormal: { count: 0, percent: 0 }
    },
    
    // 异常记录统计
    severeCount: 0,      // 重度
    moderateCount: 0,    // 中度
    mildCount: 0,        // 轻度
    elevatedCount: 0,    // 正常高值
    lowCount: 0,         // 偏低
    totalCount: 0,       // 总计
    
    isCollapsed: false,
    pieChart: null
  },

  onLoad(options) {
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight || 44
    });
    
    this.initDateRange();
    this.loadData();
  },

  onReady() {
    this.initPieChart();
  },

  initDateRange() {
    const date = new Date();
    this.setData({ currentDate: date });
    
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    
    if (this.data.timeType === 'week') {
      const weekStart = new Date(date);
      const dayOfWeek = weekStart.getDay();
      const diff = dayOfWeek === 0 ? -6 : 1 - dayOfWeek;
      weekStart.setDate(date.getDate() + diff);
      
      const weekEnd = new Date(weekStart);
      weekEnd.setDate(weekStart.getDate() + 6);
      
      const startMonth = weekStart.getMonth() + 1;
      const startDay = weekStart.getDate();
      const endMonth = weekEnd.getMonth() + 1;
      const endDay = weekEnd.getDate();
      
      this.setData({
        dateRange: `${startMonth}月${startDay}日-${endMonth}月${endDay}日`
      });
    } else if (this.data.timeType === 'day') {
      this.setData({
        dateRange: `${month}月${day}日`
      });
    } else {
      this.setData({
        dateRange: `${year}年${month}月`
      });
    }
  },

  formatDate(date) {
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${month}-${day}`;
  },

  async loadData() {
    wx.showLoading({ title: '加载中...' });
    
    try {
      const dateStr = this.formatRequestDate();
      const userInfo = userBaseInfoState.data;
      const patientUid = userInfo?.patientUid;
      
      if (!patientUid) {
        console.error('用户信息不存在');
        wx.hideLoading();
        return;
      }
      
      console.log('📋 请求参数:', { dateStr, patientUid });
      
      // 并行请求所有接口
      const [sbpRes, dbpRes, gapRes, recordRes, gradingRes] = await Promise.all([
        getSBPWeek({ anyDateInWeek: dateStr, patientUid }),
        getDBPWeek({ anyDateInWeek: dateStr, patientUid }),
        getGapWeek({ anyDateInWeek: dateStr, patientUid }),
        getRecordWeek({ anyDateInWeek: dateStr, patientUid }),
        Heartgrading({ patientUid })
      ]);
      
      console.log('📊 接口响应:', {
        sbpRes,
        dbpRes,
        gapRes,
        recordRes,
        gradingRes
      });
      
      // ========== 2. 提取接口数据 ==========
      // 收缩压数据 (Systolic Blood Pressure)
      const sbpData = sbpRes?.data || {};
      const systolicMax = sbpData.max_systolic ?? null;
      const systolicMin = sbpData.min_systolic ?? null;
      const systolicAvg = sbpData.avg_systolic ?? 0;
      const systolicMaxRisk = sbpData.max_syst_risk ?? null;
      const systolicMinRisk = sbpData.min_syst_risk ?? null;
      
      // 舒张压数据 (Diastolic Blood Pressure)
      const dbpData = dbpRes?.data || {};
      const diastolicMax = dbpData.max_diastolic ?? null;
      const diastolicMin = dbpData.min_diastolic ?? null;
      const diastolicAvg = dbpData.avg_diastolic ?? 0;
      const diastolicMaxRisk = dbpData.max_diast_risk ?? null;
      const diastolicMinRisk = dbpData.min_diast_risk ?? null;
      
      // 脉压差数据
      const gapData = gapRes?.data || {};
      const pulsePressureMax = gapData.max_pressure_diff ?? null;
      const pulsePressureMin = gapData.min_pressure_diff ?? null;
      const pulsePressureAvg = gapData.avg_pressure_diff ?? 0;
      
      console.log('✅ 提取的数据:', {
        收缩压: { max: systolicMax, min: systolicMin, avg: systolicAvg, maxRisk: systolicMaxRisk, minRisk: systolicMinRisk },
        舒张压: { max: diastolicMax, min: diastolicMin, avg: diastolicAvg, maxRisk: diastolicMaxRisk, minRisk: diastolicMinRisk },
        脉压差: { max: pulsePressureMax, min: pulsePressureMin, avg: pulsePressureAvg }
      });
      
      // ========== 3. 更新平均值显示 ==========
      this.setData({
        avgSystolic: Math.round(systolicAvg),
        avgDiastolic: Math.round(diastolicAvg)
      });
      
      // ========== 4. 更新表格数据 ==========
      // 根据API返回的数据，格式化表格数据
      // 格式：舒张压/收缩压（前两列），单个值（第三列平均值）
      const tableData = {
        systolic: {
          // 最高值：最高收缩压/对应的舒张压
          max: this.formatTableCellPaired(
            sbpData.max_systolic, 
            sbpData.max_systolic_diastolic || dbpData.max_diastolic,
            sbpData.max_systolic_risk_assessment
          ),
          // 最低值：最低收缩压/对应的舒张压
          min: this.formatTableCellPaired(
            sbpData.min_systolic,
            sbpData.min_systolic_diastolic || dbpData.min_diastolic,
            sbpData.min_systolic_risk_assessment
          ),
          // 平均值：只显示平均收缩压
          highest: this.formatTableCellSingle(
            sbpData.avg_systolic,
            sbpData.avg_systolic_risk_assessment
          )
        },
        diastolic: {
          // 最高值：最高舒张压/对应的收缩压
          max: this.formatTableCellPaired(
            dbpData.max_diastolic,
            dbpData.max_diastolic_systolic || sbpData.max_systolic,
            dbpData.max_diastolic_risk_assessment
          ),
          // 最低值：最低舒张压/对应的收缩压
          min: this.formatTableCellPaired(
            dbpData.min_diastolic,
            dbpData.min_diastolic_systolic || sbpData.min_systolic,
            dbpData.min_diastolic_risk_assessment
          ),
          // 平均值：只显示平均舒张压
          highest: this.formatTableCellSingle(
            dbpData.avg_diastolic,
            dbpData.avg_diastolic_risk_assessment
          )
        },
        pulse: {
          max: { displayValue: '--', tag: '', tagClass: '' },
          min: { displayValue: '--', tag: '', tagClass: '' },
          highest: { displayValue: '--', tag: '', tagClass: '' }
        },
        pulsePressure: {
          // 脉压差：最高值显示"脉压差/(收缩压/舒张压)"格式
          max: this.formatTableCellPulsePressure(
            gapData.max_pulse_pressure,
            gapData.max_pulse_pressure_systolic,
            gapData.max_pulse_pressure_diastolic,
            gapData.max_pulse_pressure_state
          ),
          // 脉压差：最低值显示"脉压差/(收缩压/舒张压)"格式
          min: this.formatTableCellPulsePressure(
            gapData.min_pulse_pressure,
            gapData.min_pulse_pressure_systolic,
            gapData.min_pulse_pressure_diastolic,
            gapData.min_pulse_pressure_state
          ),
          // 脉压差：平均值只显示单个值
          highest: this.formatTableCellSingle(
            gapData.avg_pulse_pressure,
            null
          )
        }
      };
      
      this.setData({ tableData });
      console.log('✅ 表格数据已更新:', tableData);
      
      // ========== 5. 处理饼图数据和异常统计（使用同一个接口） ==========
      if (gradingRes && gradingRes.code === 0 && gradingRes.data) {
        const statsData = gradingRes.data;
        
        // 更新异常记录统计
        this.setData({
          severeCount: statsData.severe || 0,
          moderateCount: statsData.moderate || 0,
          mildCount: statsData.mild || 0,
          elevatedCount: statsData.elevated || 0,
          lowCount: statsData.low || 0,
          totalCount: statsData.all || 0
        });
        
        // 更新饼图数据（使用轻度和正常高值）
        const mildCount = statsData.mild || 0;
        const elevatedCount = statsData.elevated || 0;
        const total = mildCount + elevatedCount;
        
        const mildPercent = total > 0 ? ((mildCount / total) * 100).toFixed(1) : 0;
        const elevatedPercent = total > 0 ? ((elevatedCount / total) * 100).toFixed(1) : 0;
        
        this.setData({
          pieData: {
            mild: { count: mildCount, percent: parseFloat(mildPercent) },
            highNormal: { count: elevatedCount, percent: parseFloat(elevatedPercent) }
          }
        }, () => {
          this.updatePieChart();
        });
        
        console.log('✅ 异常记录统计和饼图数据已更新');
      }
      
    } catch (error) {
      console.error('❌ 加载数据失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  formatRequestDate() {
    let date = this.data.currentDate;
    if (!(date instanceof Date)) {
      date = new Date(date);
    }
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  /**
   * 格式化表格单元格数据（配对显示：第一个值/第二个值）
   * @param {number|null} firstValue - 第一个值（舒张压或收缩压）
   * @param {number|null} secondValue - 第二个值（对应的收缩压或舒张压）
   * @param {string|null} riskLevel - 风险等级（从接口获取）
   */
  formatTableCellPaired(firstValue, secondValue, riskLevel = null) {
    // 格式化显示值
    const first = firstValue != null ? Math.round(firstValue) : '--';
    const second = secondValue != null ? Math.round(secondValue) : '--';
    const displayText = `${first}/${second}`;
    
    // 获取标签和样式
    let tag = '';
    let tagClass = '';
    
    if (riskLevel) {
      const result = this.getRiskTagFromLevel(riskLevel);
      tag = result.tag;
      tagClass = result.tagClass;
    }
    
    return {
      displayValue: displayText,
      tag: tag,
      tagClass: tagClass
    };
  },

  /**
   * 格式化表格单元格数据（单个值显示）
   * @param {number|null} value - 值
   * @param {string|null} riskLevel - 风险等级（从接口获取）
   */
  formatTableCellSingle(value, riskLevel = null) {
    // 格式化显示值
    const displayValue = value != null ? Math.round(value) : '--';
    
    // 获取标签和样式
    let tag = '';
    let tagClass = '';
    
    if (riskLevel) {
      const result = this.getRiskTagFromLevel(riskLevel);
      tag = result.tag;
      tagClass = result.tagClass;
    }
    
    return {
      displayValue: displayValue.toString(),
      tag: tag,
      tagClass: tagClass
    };
  },

  /**
   * 格式化脉压差单元格数据（显示格式：脉压差/(收缩压/舒张压)）
   * @param {number|null} pulsePressure - 脉压差值
   * @param {number|null} systolic - 对应的收缩压
   * @param {number|null} diastolic - 对应的舒张压
   * @param {string|null} riskLevel - 风险等级（从接口获取）
   */
  formatTableCellPulsePressure(pulsePressure, systolic, diastolic, riskLevel = null) {
    // 格式化显示值
    const ppValue = pulsePressure != null ? Math.round(pulsePressure) : '--';
    const sysValue = systolic != null ? Math.round(systolic) : '--';
    const diaValue = diastolic != null ? Math.round(diastolic) : '--';
    const displayText = `${ppValue}/(${sysValue}/${diaValue})`;
    
    // 获取标签和样式
    let tag = '';
    let tagClass = '';
    
    if (riskLevel) {
      const result = this.getRiskTagFromLevel(riskLevel);
      tag = result.tag;
      tagClass = result.tagClass;
    }
    
    return {
      displayValue: displayText,
      tag: tag,
      tagClass: tagClass
    };
  },

  /**
   * 根据接口返回的风险等级字符串获取标签
   */
  getRiskTagFromLevel(riskLevel) {
    const riskMap = {
      '正常': { tag: '正常', tagClass: 'normal' },
      '正常高值': { tag: '正常高值', tagClass: 'high-normal' },
      '轻度': { tag: '轻度', tagClass: 'mild' },
      '轻度高血压': { tag: '轻度', tagClass: 'mild' },
      '中度': { tag: '中度', tagClass: 'moderate' },
      '中度高血压': { tag: '中度', tagClass: 'moderate' },
      '重度': { tag: '重度', tagClass: 'severe' },
      '重度高血压': { tag: '重度', tagClass: 'severe' },
      '强高': { tag: '强高', tagClass: 'severe' },
      '偏低': { tag: '偏低', tagClass: 'low' }
    };
    
    return riskMap[riskLevel] || { tag: '', tagClass: '' };
  },

  /**
   * 根据数值计算风险等级
   */
  calculateRiskLevel(value, type) {
    if (type === 'systolic') {
      // 收缩压分级标准
      if (value >= 180) {
        return { tag: '重度', tagClass: 'severe' };
      } else if (value >= 160) {
        return { tag: '中度', tagClass: 'moderate' };
      } else if (value >= 140) {
        return { tag: '轻度', tagClass: 'mild' };
      } else if (value >= 130) {
        return { tag: '正常高值', tagClass: 'high-normal' };
      } else if (value >= 90) {
        return { tag: '正常', tagClass: 'normal' };
      } else {
        return { tag: '偏低', tagClass: 'low' };
      }
    } else if (type === 'diastolic') {
      // 舒张压分级标准
      if (value >= 110) {
        return { tag: '重度', tagClass: 'severe' };
      } else if (value >= 100) {
        return { tag: '中度', tagClass: 'moderate' };
      } else if (value >= 90) {
        return { tag: '轻度', tagClass: 'mild' };
      } else if (value >= 85) {
        return { tag: '正常高值', tagClass: 'high-normal' };
      } else if (value >= 60) {
        return { tag: '正常', tagClass: 'normal' };
      } else {
        return { tag: '偏低', tagClass: 'low' };
      }
    } else if (type === 'pulsePressure') {
      // 脉压差分级标准
      if (value >= 60) {
        return { tag: '过高', tagClass: 'severe' };
      } else if (value > 50) {
        return { tag: '偏高', tagClass: 'high-normal' };
      } else if (value >= 30) {
        return { tag: '正常', tagClass: 'normal' };
      } else {
        return { tag: '偏低', tagClass: 'mild' };
      }
    } else if (type === 'pulse') {
      // 脉率分级标准
      if (value >= 100) {
        return { tag: '偏快', tagClass: 'high-normal' };
      } else if (value >= 60) {
        return { tag: '正常', tagClass: 'normal' };
      } else {
        return { tag: '偏慢', tagClass: 'mild' };
      }
    }
    
    return { tag: '', tagClass: '' };
  },


  // 初始化饼图
  initPieChart() {
    setTimeout(() => {
      const query = wx.createSelectorQuery().in(this);
      query.select('#distributionPie')
        .fields({ node: true, size: true })
        .exec((res) => {
          if (res && res[0] && res[0].node) {
            const canvas = res[0].node;
            const ctx = canvas.getContext('2d');
            
            const dpr = wx.getSystemInfoSync().pixelRatio || 2;
            
            canvas.width = res[0].width * dpr;
            canvas.height = res[0].height * dpr;
            ctx.scale(dpr, dpr);

            this.pieCanvasInfo = {
              canvas,
              ctx,
              width: res[0].width,
              height: res[0].height
            };

            try {
              this.pieChart = echarts.init(canvas, null, {
                width: res[0].width,
                height: res[0].height,
                devicePixelRatio: dpr
              });
              
              console.log('✅ 饼图(ECharts)初始化成功');
              this.updatePieChart();
            } catch (error) {
              console.warn('⚠️ ECharts初始化失败，使用Canvas绘制:', error);
              this.drawPieChartWithCanvas();
            }
          } else {
            console.error('❌ 饼图Canvas节点未找到');
          }
        });
    }, 300);
  },

  // 更新饼图
  updatePieChart() {
    if (!this.pieChart && !this.pieCanvasInfo) {
      console.warn('⚠️ 饼图未初始化，稍后重试');
      clearTimeout(this._pieRetryTimer);
      this._pieRetryTimer = setTimeout(() => this.updatePieChart(), 300);
      return;
    }
    
    const pieData = this.data.pieData;
    
    if (this.pieChart) {
      try {
        const chartData = [];
        
        if (pieData.mild.count >= 0) {
          chartData.push({ 
            value: pieData.mild.count, 
            name: '轻度',
            percent: pieData.mild.percent 
          });
        }
        
        if (pieData.highNormal.count > 0) {
          chartData.push({ 
            value: pieData.highNormal.count, 
            name: '正常高值',
            percent: pieData.highNormal.percent 
          });
        }
        
        if (chartData.length === 0) {
          chartData.push({ value: 1, name: '暂无数据', itemStyle: { color: '#E5E5E5' } });
        }
        
        const option = {
          color: ['#1867EB', '#3CDFF5'],
          series: [{
            type: 'pie',
            radius: ['50%', '70%'],
            center: ['50%', '50%'],
            avoidLabelOverlap: false,
            label: {
              show: false
            },
            labelLine: {
              show: false
            },
            emphasis: {
              scale: true,
              scaleSize: 5
            },
            data: chartData
          }]
        };
        
        this.pieChart.setOption(option, true);
        console.log('✅ 饼图(ECharts)已更新');
      } catch (error) {
        console.warn('⚠️ ECharts更新失败，使用Canvas绘制:', error);
        this.drawPieChartWithCanvas();
      }
    } else {
      this.drawPieChartWithCanvas();
    }
  },


  // 使用原生 Canvas 绘制环形饼图（ECharts 初始化失败时的兜底方案）
  drawPieChartWithCanvas() {
    const info = this.pieCanvasInfo;
    if (!info) {
      console.warn('⚠️ Canvas信息不存在，无法绘制饼图');
      return;
    }
    const { ctx, width, height } = info;
    const pieData = this.data.pieData || { mild: { count: 0 }, highNormal: { count: 0 } };
    const mild = Number(pieData.mild?.count || 0);
    const high = Number(pieData.highNormal?.count || 0);
    const total = mild + high;

    // 画布准备
    ctx.clearRect(0, 0, width, height);

    const cx = width / 2;
    const cy = height / 2;
    const outerR = Math.min(width, height) / 2 * 0.9; // 外半径
    const innerR = outerR * 0.6;                       // 内半径（空心）
    const ringW = outerR - innerR;                     // 圆环宽度

    // 没有数据时绘制灰色占位圆环
    if (total <= 0) {
      ctx.beginPath();
      ctx.lineWidth = ringW;
      ctx.strokeStyle = '#E5E5E5';
      ctx.arc(cx, cy, innerR + ringW / 2, -Math.PI / 2, Math.PI * 1.5, false);
      ctx.stroke();
      return;
    }

    // 绘制函数
    const drawRing = (startAngle, ratio, color) => {
      if (ratio <= 0) return startAngle;
      const endAngle = startAngle + Math.PI * 2 * ratio;
      ctx.beginPath();
      ctx.lineWidth = ringW;
      ctx.lineCap = 'butt';
      ctx.strokeStyle = color;
      ctx.arc(cx, cy, innerR + ringW / 2, startAngle, endAngle, false);
      ctx.stroke();
      return endAngle;
    };

    // 从12点方向开始
    let angle = -Math.PI / 2;
    angle = drawRing(angle, mild / total, '#1867EB');      // 轻度
    angle = drawRing(angle, high / total, '#3CDFF5');      // 正常高值

    // 中心标题
    ctx.fillStyle = '#111111';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.font = '14px PingFang SC, sans-serif';
    ctx.fillText('基本情况', cx, cy);
  },


  onTimeTypeChange(e) {
    const type = e.detail?.type || e.currentTarget?.dataset?.type;
    if (type) {
      // 切换时间类型时，重置所有计数器为0
      this.setData({ 
        timeType: type,
        daysAgo: 0,
        weeksAgo: 0,
        monthsAgo: 0
      });
      this.initDateRange();
      this.loadData();
    }
  },

  onPrevDate() {
    const timeType = this.data.timeType;
    const date = this.data.currentDate;
    
    // 更新计数器
    if (timeType === 'day') {
      this.setData({ daysAgo: this.data.daysAgo + 1 });
      date.setDate(date.getDate() - 1);
    } else if (timeType === 'week') {
      this.setData({ weeksAgo: this.data.weeksAgo + 1 });
      date.setDate(date.getDate() - 7);
    } else if (timeType === 'month') {
      this.setData({ monthsAgo: this.data.monthsAgo + 1 });
      date.setMonth(date.getMonth() - 1);
    }
    
    this.setData({ currentDate: date });
    this.initDateRange();
    this.loadData();
  },

  onNextDate() {
    const timeType = this.data.timeType;
    const date = this.data.currentDate;
    
    // 更新计数器（不能小于0）
    if (timeType === 'day') {
      const newDaysAgo = Math.max(0, this.data.daysAgo - 1);
      this.setData({ daysAgo: newDaysAgo });
      if (newDaysAgo < this.data.daysAgo) {
        date.setDate(date.getDate() + 1);
      }
    } else if (timeType === 'week') {
      const newWeeksAgo = Math.max(0, this.data.weeksAgo - 1);
      this.setData({ weeksAgo: newWeeksAgo });
      if (newWeeksAgo < this.data.weeksAgo) {
        date.setDate(date.getDate() + 7);
      }
    } else if (timeType === 'month') {
      const newMonthsAgo = Math.max(0, this.data.monthsAgo - 1);
      this.setData({ monthsAgo: newMonthsAgo });
      if (newMonthsAgo < this.data.monthsAgo) {
        date.setMonth(date.getMonth() + 1);
      }
    }
    
    this.setData({ currentDate: date });
    this.initDateRange();
    this.loadData();
  },

  toggleCollapse() {
    this.setData({
      isCollapsed: !this.data.isCollapsed
    });
  },

  onAddRecord() {
    wx.navigateTo({
      url: '../PressureRecord/heart_rate/heart_rate'
    });
  },

  onBack() {
    wx.navigateBack();
  },

  onShareAppMessage() {
    return {
      title: '血压记录',
      path: '/pages/home/PressureRecord/index'
    };
  }
});
